#!/bin/env python
# coding=utf8
#首图搜索
import os, urllib
import re
from BeautifulSoup import BeautifulSoup
from google.appengine.api import urlfetch 
from google.appengine.api import memcache as mc

def query_isbn(isbn):
    params = urllib.urlencode({'SearchFld1': 5, 
                                'SearchFld2': 2, 
                                'SearchFld3': 3, 
                                'SearchLib': 10, 
                                'SearchTxt1': isbn})
    url = "http://query.clcn.net.cn/PubQueryCls.ASP?WCI=BookQueryAdv&WCE=Form1&WCU"    
    header = {'Content-Type': 'application/x-www-form-urlencoded'}
    result = urlfetch.fetch(url=url,
                payload=params,
                method=urlfetch.POST,
                headers=header)
    html = result.content
    return html

def get_book_url(isbn):
    key = str(isbn)
    data = mc.get(key)
    if data:
        return data
    html = query_isbn(isbn)
    soup = BeautifulSoup(''.join(html))
    td = []
    if len(soup('tr'))>10:
        for i in range(2,7):
            t = soup('table', height="214")[0].contents[1].contents[i]
            if i==2:
                url = t.contents[0].contents[0]["href"]
                t.contents[0].contents[0]["href"] = "http://query.clcn.net.cn/" + url
            td.append(t)
    mc.set(key, td, 3600*24*7)
    return  td
